package com.eatme.web.filter;

import com.eatme.web.exception.VerificationCodeException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class VerificationCodeFilter extends OncePerRequestFilter {

    private static final Logger LOG = LoggerFactory.getLogger(VerificationCodeFilter.class);

    AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler() {
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
            LOG.info("异常:{}",exception.getMessage());
            response.sendRedirect("/login");
        }
    };
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (!("/login".equals(request.getRequestURI()) && request.getMethod().equals("POST"))) {
            filterChain.doFilter(request,response);
        }else {
            try {
                verificationCode(request,response);
                filterChain.doFilter(request,response);
            }catch (VerificationCodeException e) {
                authenticationFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
    }

    private void verificationCode(HttpServletRequest request, HttpServletResponse response) {
        String requestCode = request.getParameter("captcha");
        HttpSession session = request.getSession();
        String sessionCode = (String) session.getAttribute("captcha");
        if (!StringUtils.isEmpty(sessionCode)) {
            session.removeAttribute("captcha");
        }
        if(StringUtils.isEmpty(requestCode)||StringUtils.isBlank(sessionCode)||!requestCode.equals(sessionCode)) {
            throw new VerificationCodeException();
        }
    }
}
